<template>
  <div>
    <div class="searchBox">
      <el-input v-model="searchTableInfo" prefix-icon="iconfont icon-sousuo" placeholder="请输入搜索内容" style="width:240px" />
      <el-cascader v-model="categories" style="width:240px;margin-left: 20px" expand-trigger="hover" :options="catelist" :props="cateProps"  @change="handleChange" />
    </div>
    <el-table
      :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
      border
      style="width: 100%;margin: 10px 0;text-align:center;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column fixed prop="id" label="编号" width="120" />
      <el-table-column prop="bookName" label="书名" width="120" />
      <el-table-column prop="cover" label="图片" width="120" align="center">
        <template slot-scope="scope">
          <el-popover placement="right" title="" trigger="hover">
            <img :src="scope.row.cover ">
            <img slot="reference" :src="scope.row.cover" :alt="scope.row.cover" style="max-height: 50px;max-width: 130px">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="定价" width="120" />
      <el-table-column prop="author" label="作者" width="120" />
      <el-table-column prop="press" label="出版社" width="120" />
      <el-table-column prop="publishingTime" label="出版时间" width="120" />
      <el-table-column prop="printingTime" label="印刷时间" width="120" />
      <el-table-column prop="firstcategory" label="一级分类" width="120" />
      <el-table-column prop="secondcategory" label="二级分类" width="120" />

      <!-- 操作区域 -->
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="edit(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="deleteBook(scope.row.id, scope.row.bookName)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.length"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import userApi from '@/api/user'

export default {
  data() {
    return {
      // 搜索条件
      searchTableInfo: '',
      pageSize: 5,
      currentPage: 1,
      getSearchInfo: [],
      categories: [],
      // 商品分类列表
      catelist: [],
      cateProps: {
        label: 'title',
        value: 'id',
        children: 'children'
      }
    }
  },
  computed: {
    // 根据计算属性模糊搜索
    tableData() {
      const searchTableInfo = this.searchTableInfo
      if (searchTableInfo) {
        return this.getSearchInfo.filter(data => {
          return Object.keys(data).some(key => {
            return String(data[key]).toLowerCase().indexOf(searchTableInfo) > -1
          })
        })
      }
      return this.getSearchInfo
    }
  },
  created() {
    this.info()
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.post('/bookcity/category/getAllCategory')
      if (res.data === 'success') { return this.$message.success('获取商品分类成功！') }
      // console.log(res.data)
      // 把数据列表，赋值给 catelist
      this.catelist = res.data.data
    },
    // 级联选择器选中项变化范围
    async handleChange() {
      // async + await 同步请求  避免axios嵌套
      const categoryItems = await this.getbookbyCategory()
      this.getSearchInfo = []
      categoryItems.forEach(element => {
        this.$http.get('/bookcity/book/getbookbyid/' + element.id)
          .then(resp => {
            this.getSearchInfo.push(resp.data.data[element.id])
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    getbookbyCategory() {
      if (this.categories.length !== 2) {
        this.categories = []
      }
      return new Promise(resolve => {
        this.$http.get('/bookcity/book/getbookbyCategory/' + this.categories[0] + '/' + this.categories[1])
          .then(res => {
            resolve(res.data.data.books)
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    // 每页条数改变触发时，选择一页显示多少行
    handleSizeChange(newSize) {
      this.pageSize = newSize
    },
    // 页面改变时触发跳转
    handleCurrentChange(newPage) {
      this.currentPage = newPage
    },
    // 操作多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取所有书信息
    info() {
      userApi.getAllbooks().then(res => {
        // console.log(res.data)
        // this.$message.success('获取商品列表成功！')
        // this.tableData = res.data.data.books;
        this.getSearchInfo = res.data.data.books
      }, err => {
        console.log(err)
      })
    },

    // 删除图书（根据id）
    deleteBook(id, bookName) {
      userApi.deleteBookById(id).then(res => {
        // console.log(res.data)
        this.$alert('《' + bookName + '》删除成功', '消息提示', {
          confirmButtonText: '确定',
          callback: action => {
            window.location.reload()
          }
        })
      }, err => {
        this.$message.error('删除失败')
        console.log(err)
      })
    },

    // 修改图书
    edit(row) {
      this.$router.push(
        { path: '/BookUpdate', name: '图书管理里的修改', params: { id: row.id }}
      )
      // console.log(row.id)
    }
  }
}
</script>

<style scoped lang="stylus">

</style>

